package us.sunrisemorning.douyuchat;

import java.io.UnsupportedEncodingException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.Tio;

import com.google.common.eventbus.Subscribe;

public class MessageListener {
    private static Logger log = LoggerFactory.getLogger(MessageListener.class);

    private final String roomId;
    private final MessageHandler handler;

    public MessageListener(String roomId, MessageHandler handler) {
        this.roomId = roomId;
        this.handler = handler;
    }

    @Subscribe
    public void listen(MessageEvent event) {
        try {
            byte[] body = event.getBody();
            String str = new String(body, 0, body.length - 1, MessagePacket.BODY_CHARSET);
            Message message = MessageUtils.decode(str);
            switch (message.getType()) {
            case "loginres":
                Tio.send(event.getChannelContext(), MessageMaker.joingroup(roomId));
                break;
            default:
                handler.handle(message);
                break;
            }
        } catch (UnsupportedEncodingException e) {
            log.error("decode error", e);
        }
    }
}
